﻿using MusicPlayerPlus.Interface.Base;
using MusicPlayerPlus.Interface.Model.Muisc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MusicPlayerPlus.PlugIn.MusicData
{
    public class MusicData : InterfaceBase,
        //Input
        MusicPlayerPlus.Interface.Base.Action.Input.IAutoExecuteAction,
        MusicPlayerPlus.Interface.Base.Action.Input.IPlayListChange,
        //Output
        MusicPlayerPlus.Interface.Base.Action.Output.IAddPlayListAction
    {
        IDictionary<Guid, PlayList> playListData = null;
        /// <summary>
        /// 自动执行动作接口
        /// </summary>
        public void AutoExecute()
        {
            playListData = ReadPlayListData();
            foreach (var item in playListData)
            {
                AddPlayList_Action(item.Value);
            }
        }

        /// <summary>
        /// 播放列表改变时
        /// </summary>
        public void PlayListChange(Guid guid, PlayList list)
        {
            if (playListData.ContainsKey(guid))
            {
                if (list != null)
                {
                    playListData[guid] = list;
                    SavePlayListData(playListData);
                }
                else
                {
                    playListData.Remove(guid);
                    SavePlayListData(playListData);
                }
            }
            else
            {
                if (list != null)
                {
                    if (list.Type == Interface.Model.Enum.PlayListType.Normal)
                    {
                        playListData.Add(guid, list);
                        SavePlayListData(playListData);
                    }
                }
            }
        }

        /// <summary>
        /// 添加播放列表
        /// </summary>
        public Func<PlayList, bool> AddPlayList_Action { private get; set; }

        #region Method

        private IDictionary<Guid, PlayList> ReadPlayListData()
        {
            string data = Method.Data.LocaData.ReadData("MusicData");
            if (string.IsNullOrEmpty(data))
            {
                return new Dictionary<Guid, PlayList>();
            }
            return Method.Helper.JsonHelper.Deserialize<Dictionary<Guid, PlayList>>(data);
        }

        private void SavePlayListData(IDictionary<Guid, PlayList> data)
        {
            string json = Method.Helper.JsonHelper.Serialize(data);
            Method.Data.LocaData.SaveData("MusicData", json);
        }

        #endregion
    }
}
